import axios from 'axios'
import { Notification } from 'element-ui'

const http = axios.create({
  baseURL: '/api',
  timeout: 30 * 1000
})

const message = (message: string) => Notification.error({
  title: '错误',
  message,
  type: 'error'
})

http.interceptors.response.use(function (response) {
  if (response.status !== 200) {
    message(response.statusText)
    return Promise.reject(response)
  } else {
    if (response.data?.code !== 200) {
      const msg = response.data?.message || response.data?.data
      message(msg)
      return Promise.reject(response)
    } else {
      return Promise.resolve(response.data?.data)
    }
  }
}, function (error) {
  message(error?.message || error)
  return Promise.reject(error)
})

export default {
  install: function (Vue: any, options: any) {
    Vue.prototype.$http = http
  }
}

export { http }
